#include "tcp.h"

TCP::TCP(QObject *parent) : QObject(parent)
{
    //监听套接字,指定父类对象，让其自动回收空间

    tcpServe=new QTcpServer(this);
    tcpServe->listen(QHostAddress::Any,this->port.toInt());
    connect(tcpServe,&QTcpServer::newConnection,[=](){
            //取出建立好连接的套接字
            tcpSocket=tcpServe->nextPendingConnection();
            //获取对方的ip和端口
            QString ip=tcpSocket->peerAddress().toString();
            qint16 por=tcpSocket->peerPort();
            QString temp=QString("[%1:%2]:成功连接...").arg(ip).arg(por);
            connect(tcpSocket,&QTcpSocket::readyRead,[=](){
                //从通信套接字中取出内容
                QByteArray array=tcpSocket->readAll();
                qDebug()<<"info"<<array.data();
            });
    });
}

void TCP::Send(QString str)
{
    if(tcpServe==nullptr){
        return;
    }
    //给对方发送数据，使用弹出tcpSocket套接字
    tcpSocket->write(str.toUtf8().data());
}

QString TCP::getPort()
{
    return port;
}

void TCP::setPort(QString port)
{
    this->port = port;
}
